<!DOCTYPE html>
<meta charset="utf-8">

<style>

    {% if request.session.topo != "tree" %}
    .row-center {
        text-align: center;
    }

    .link {
        fill: none;
        stroke: #666;
        stroke-width: 1.5px;
    }

    .node circle {
        fill: #ccc;
        stroke: #fff;
        stroke-width: 1.5px;
    }

    text {
        pointer-events: none;
    }

    .tooltip {
        text-decoration: underline;
    }

    {% else %}

    .node {
          cursor: pointer;
        }
        .node circle {
          fill: #fff;
          stroke: steelblue;
          stroke-width: 1.5px;
        }

        .node text {
          font: 14px sans-serif;
        }

        .link {
          fill: none;
          stroke: #ccc;
          stroke-width: 1.5px;
        }
    {% endif%}
</style>

<head>
<title>bitoin网络拓扑图</title>
<!-- Bootstrap core CSS -->
<link href="{{ STATIC_URL }}/static/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

    <div class="row-center"><h1>比特币网络分布图</h1></div>
	<div>
     <svg width="100%" height="500px" id="forcesvg">
	 <g id="tooltip2"></g>
    </svg>
		<button class="btn btn-danger" style="float:right;margin-right: 20px;color:#007bff;background-color:#fff;border:1px solid #ddd" onclick="addNode()"> 新增节点 </button >
		<button class="btn btn-danger" style="float:right;margin-right: 20px;color:#007bff;background-color:#fff;border:1px solid #ddd" onclick="delNode()"> 删除节点 </button >
    </div>
	
	<div class="col-lg-12">
        <div class="panel panel-info">
            <div class="panel-heading">
                {{ host_name }}节点具体信息
            </div>
            <div class="panel-body">
                    <div class="col-lg-6">
						<div class="form-group">
                                <label style="padding-top:5px">节点ID</label>
                                <p class="help-block" style="width:50%; float:right">{{ base_info.0 }}</p>
                        </div>
					</div>
					<div class="col-lg-3">
						<div class="form-group">
                                <label style="padding-top:5px">节点地址</label>
                                <p class="help-block" style="width:50%; float:right">{{ base_info.1 }}</p>
                        </div>
					</div>
					<div class="col-lg-3">
                        {% if request.session.type == "BGP" %}
						<button class="btn btn-danger"  onclick="mine('{{ host_name }}')"> 执行挖矿 </button >
                        <button class="btn btn-danger"  onclick="BGPattack('{{ host_name }}')"> BGP攻击 </button >
                        {% endif%}
                        {% if request.session.type == "PBFT" %}
                        <button class="btn btn-danger"  onclick="PBFT('{{ host_name }}')"> PBFT </button >
                        {% endif%}
						<br></br>
						<input class="form-control"  style="width:45%; display:inline" placeholder="对方节点" id="receiver">
						<input class="form-control"  style="width:45%; display:inline" placeholder="交易额" id="amount">
						<button class="btn btn-danger"  onclick="createTX('{{ host_name }}')"> 发送交易 </button >
					</div>
                    <div class="col-lg-3">
						<div class="form-group">
                                <label style="padding-top:5px">钱包余额</label>
                                <p class="help-block" style="width:50%; float:right">{{ wallet_info }}</p>
                        </div>
					</div>
            </div>
			<div class="panel-heading">
                {{ host_name }}节点未确认交易列表
            </div>
			<div class="panel-body">
                {% for tx in tx_info %}
                    <div class="col-lg-3">
						<div class="form-group">
                                <label style="padding-top:5px">交易ID</label>
                                <p class="help-block" style="width:50%; ">{{ tx.id }}</p>
                        </div>
					</div>
					<div class="col-lg-3">
						<div class="form-group">
                                <label style="padding-top:5px">发送方ID</label>
                                <p class="help-block" style="width:50%;">{{ tx.sender }}</p>
                        </div>
					</div>
					<div class="col-lg-3">
						<div class="form-group">
                                <label style="padding-top:5px">接收方ID</label>
                                <p class="help-block" style="width:50%;">{{ tx.recipient }}</p>
                        </div>
					</div>
					<div class="col-lg-1">
						<div class="form-group">
                                <label style="padding-top:5px">交易额</label>
                                <p class="help-block" style="width:50%;">{{ tx.amount }} bitcoin</p>
                        </div>
					</div>
                {% endfor %}
            </div>
			
			<div class="panel-heading">
                {{ host_name }}节点区块链信息
            </div>
        {% for block in block_info %}
			<div class="panel-body">

                    <div class="col-lg-1" style="width:0.5%;padding-left:0px">
						<div class="form-group">
                                <label style="padding-top:5px">ID</label>
                                <p class="help-block" style="width:50%; ">{{ block.index }}</p>
                        </div>
					</div>
					<div class="col-lg-1" style="width:2.5%">
						<div class="form-group">
                                <label style="padding-top:5px">proof</label>
                                <p class="help-block" style="width:50%;">{{ block.proof }}</p>
                        </div>
					</div>
					<div class="col-lg-3" style="width:21.5%">
						<div class="form-group">
                                {% if request.session.type == "PBFT" %}
                                    <label style="padding-top:5px">节点ID</label>
                                {% else %}
                                    <label style="padding-top:5px">矿工ID</label>
                                {% endif%}

                                <p class="help-block" style="width:50%;">{{ block.minerID }}</p>
                        </div>
					</div>
					<div class="col-lg-1" style="width:5%; padding-right:0px">
						<div class="form-group">
                                <label style="padding-top:5px">矿工奖励</label>
                                <p class="help-block" style="width:50%;">{{ block.minerAmount }}&nbspBTC</p>
                        </div>
					</div>
					<div class="col-lg-3" style="width:21.5%">
						<div class="form-group">
                                <label style="padding-top:5px">已确认交易ID</label>
                            {% for tx in block.transactions %}
                                <p class="help-block" style="width:50%;">{{ tx.id }}</p>
                                {% endfor %}
                        </div>
					</div>
                    <div class="col-lg-3" style="width:21%">
						<div class="form-group">
                                <label style="padding-top:5px">发送方ID</label>
                            {% for tx in block.transactions %}
                                <p class="help-block" style="width:50%;">{{ tx.sender }}</p>
                                {% endfor %}
                        </div>
					</div>
                    <div class="col-lg-3" style="width:21.5%">
						<div class="form-group">
                                <label style="padding-top:5px">接收方ID</label>
                            {% for tx in block.transactions %}
                                <p class="help-block" style="width:50%;">{{ tx.recipient }}</p>
                                {% endfor %}
                        </div>
					</div>
                    <div class="col-lg-1" style="width:5% ; padding-right:0px">
						<div class="form-group">
                                <label style="padding-top:5px">交易额</label>
                            {% for tx in block.transactions %}
                                <p class="help-block" style="width:50%;">{{ tx.amount }}&nbspBTC</p>
                                {% endfor %}
                        </div>
					</div>
            </div>
			{% endfor %}
            <div class="panel-footer">
            </div>
        </div>
    </div>
	
	

    <script src="{{ STATIC_URL }}/static/js/d3.v3.min.js"></script>
    <script src="{{ STATIC_URL }}/static/js/jquery-3.3.1.min.js"></script>

    <script>

        {% if request.session.topo != "tree" %}
            d3.json("{{ STATIC_URL }}/static/data/p2p.json", function (err, links) {
            var color = d3.scale.category20();

            var nodes = {};

            // 从links计算nodes
            links.forEach(function (link) {
                link.source = nodes[link.source] || (nodes[link.source] = { name: link.source, region: link.region });
                link.target = nodes[link.target] || (nodes[link.target] = { name: link.target, region: link.region });
            });

            var width = 1280,
                height = 700;

            var edge = 80;
            var charge = -3200;
            {% if request.session.topo == "net" %}
                edge = 150;
            {% elif request.session.topo == "star" and request.session.type == "BGP" %}
                charge = -800;
            {% endif %}

            // 力布局
            var force = d3.layout.force()
                .nodes(d3.values(nodes))
                .links(links)
                .size([width, height])
                .linkDistance(edge)
                .charge(charge)
                .on("tick", tick)
                .start();


			var svg = d3.select("#forcesvg");

            var link = svg.selectAll(".link")
                .data(force.links())
                .enter().append("line")
                .attr("class", "link");

			// 定义tooltip,在svg上加上class g的标签
			var tooltip = d3.select("#tooltip2");



            tooltip.append("text")
                .attr("x", 15)
                .attr("dy", "1.2em")
                .style("font-size", "1.35em")
                .attr("font-weight", "bold");

            // 添加node及鼠标事件
            var node = svg.selectAll(".node")
                .data(force.nodes())
                .enter().append("g")
                .attr("class", "node")
                .on("mouseover", mouseover)
                .on("mouseout", mouseout)
				.on("click", click)
                .call(force.drag);

            node.append("circle")
                .style("fill", function (d) {
                    return color(d.region);
                })
                .attr("r", 16);

            node.append("text")
                .attr("x", 12)
                .attr("dy", ".35em")
                .text(function (d) {
                    return d.name;
                });

            //定义鼠标移到圆形上的操作
            node.on("mousemove", function (d) {
                //获取圆形的坐标
                var xPos = d.x - 50;
                var yPos = d.y - 45;
                tooltip.attr("transform", "translate(" + xPos + "," + yPos + ")");
                tooltip.select("text").text(d.region);
            });

            function tick() {
                link
                    .attr("x1", function (d) {
                        return d.source.x;
                    })
                    .attr("y1", function (d) {
                        return d.source.y;
                    })
                    .attr("x2", function (d) {
                        return d.target.x;
                    })
                    .attr("y2", function (d) {
                        return d.target.y;
                    });

                node
                    .attr("transform", function (d) {
                        return "translate(" + d.x + "," + d.y + ")";
                    });
            }

            function mouseover() {
                tooltip.style("display", null);
                d3.select(this).select("circle").transition()
                    .duration(750)
                    .attr("r", 20);
            }

            function mouseout() {
                tooltip.style("display", "none");
                d3.select(this).select("circle").transition()
                    .duration(750)
                    .attr("r", 16);
            }

			function click() {
            //    alert(d3.select(this).select("text").text());
            //    $.get("/get_node_info", {'hostname':d3.select(this).select("text").text()});
                window.location.href = "get_node_info?hostname="+d3.select(this).select("text").text();
			//	ocation.reload();
			//	alert();
            }
            });

        {% else %}

            var width = 1280,
                height = 800;

            var i = 0,
                duration = 3000,
                root;

            var tree = d3.layout.tree()
                .size([120, 100])  //360´ú±íÕ¹¿ªµÄ×î´ó½Ç¶ÈÒ²¾ÍÊÇÔ²£¬ºóÃæµÄrÖµ´ú±íÕû¸ö·øÉä²¼¾ÖµÄÕ¹¿ª×î´ó°ë¾¶£¬²¢²»ÊÇÖ¸Ä³Ò»²ã¼¶µÄ°ë¾¶¶øÊÇÕû¸öÊ÷,³¬¹ýÕâ¸ö·¶Î§µÄ¾Í²»ÏÔÊ¾ÁË£¬ºóÃæ85ÐÐd.yµÄ²ÅÊÇÄ³Ò»²ã¼¶µÄ°ë¾¶ÉèÖÃ¡£
                .separation(function(a, b) {
                    return (a.parent == b.parent ? 1 : 2) / a.depth;  //ÊÊÓ¦radial²¼¾Ö£¬¿ÉÒÔ¼òµ¥µÄÀí½âÎªÉî¶ÈÔ½¸ß£¬ÏàÁÚ×Ó½ÚµãÖ®¼äµÄ¾àÀëÔ½Ð¡¡£
                });

            var diagonal = d3.svg.diagonal.radial()
                .projection(function(d) { return [d.y, d.x / 180 * Math.PI]; }); //d.y´ú±í°ë¾¶£¬(d.x/180)*PI¾ÍÊÇ¸÷¸ö½ÚµãµÄ»¡¶È±íÊ¾¡£

	        var svg = d3.select("#forcesvg")
		        .attr("width", width)
                .attr("height", height)
                .append("g")
                .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");



            d3.json("{{ STATIC_URL }}/static/data/p2p-tree.json", function(error, flare) {
                if (error) throw error;

                    root = flare;
                    root.x0 = height / 2;  //ÓÉÓÚÊÇ·øÉä²¼¾ÖÕâ±ßµ±y0ÉèÖÃÎª0,ÄÇÃ´Õâ¸ö½Ç¶Èx0Ëæ±ãÉèÖÃÒ²ÎÞËùÎ½ ÒòÎª¿Ï¶¨ÊÇÔÚÔ²ÐÄ¡£ÕâÀïµÄÀí½â²»ÖªµÀ¶Ô²»¶Ô
                    root.y0 = 0;


                function collapse(d) {
                    if (d.children) {
                        d._children = d.children;
                        d._children.forEach(collapse);
                        d.children = null;
                    }
                }

            // root.children.forEach(collapse);
                update(root);
            });

            // Hack to make this example display correctly in an iframe on bl.ocks.org ÎªÁËÔÚiframeÖÐÕý³£ÏÔÊ¾¶øÒÑ¡£
            d3.select(self.frameElement).style("height", "800px");

            function update(source) {

                // Compute the new tree layout.
                var nodes = tree.nodes(root),
                links = tree.links(nodes);

                // Normalize for fixed-depth. ¸ù¾ÝÉî¶ÈÀ´¸ø¶¨ÏàÓ¦°ë¾¶£¬Ò²¾ÍÊÇÉî¶ÈÔ½´ó°ë¾¶Ô½³¤¡£
                nodes.forEach(function(d) { d.y = d.depth * 120; });

                // Update the nodes¡­
                var node = svg.selectAll("g.node")
                    .data(nodes, function(d) { return d.id || (d.id = ++i); });


                // Enter any new nodes at the parent's previous position.
                var nodeEnter = node.enter().append("g")
                    .attr("class", "node")
                    .on("click", click);

                nodeEnter.append("circle")
                    .attr("r", 1e-6)
                    .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

                nodeEnter.append("text")
                    .attr("x", function(d) { return d.children || d._children ? -15 : 10; })
                    .attr("dy", ".35em")
                    .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })//Ð¡ÓÚ180¶ÈµÄÎÄ×Ö·ÅÔÚÇ°Ãæ£¬·ñÔò·ÅÔÚºóÃæ
                    .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; })
                    .text(function(d) { return d.name; })
                    .style("fill-opacity", 1e-6);


                // Transition nodes to their new position.
                var nodeUpdate = node.transition()
                    .duration(duration)
                    .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })

                nodeUpdate.select("circle")
                    .attr("r", 16)
                    .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

                nodeUpdate.select("text")
                    .style("fill-opacity", 1);

                // Transition exiting nodes to the parent's new position.
                var nodeExit = node.exit().transition()
                    .duration(duration)
                    .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
                    .remove();

                nodeExit.select("circle")
                    .attr("r", 1e-6);

                nodeExit.select("text")
                    .style("fill-opacity", 1e-6);

                // Update the links¡­
                var link = svg.selectAll("path.link")
                    .data(links, function(d) { return d.target.id; });

                // Enter any new links at the parent's previous position.
                link.enter().insert("path", "g")
                    .attr("class", "link")
                    .attr("d", function(d) {
                    var o = {x: source.x0, y: source.y0};
                    return diagonal({source: o, target: o});
                });

                // Transition links to their new position.
                link.transition()
                    .duration(duration)
                    .attr("d", diagonal);

                // Transition exiting nodes to the parent's new position.
                link.exit().transition()
                    .duration(duration)
                    .attr("d", function(d) {
                    var o = {x: source.x0, y: source.y0};
                    return diagonal({source: o, target: o});
                }).remove();

                // Stash the old positions for transition.
                nodes.forEach(function(d) {
                    d.x0 = d.x;
                    d.y0 = d.y;
                });
            }

            // Toggle children on click.
            function click(d) {
                if (d.children) {
                    d._children = d.children;
                    d.children = null;
                } else {
                    d.children = d._children;
                    d._children = null;
		            if(d.name.substr(0, 1)!="s"){
		                window.location.href = "get_node_info?hostname="+d.name;
{#			            alert("fuck you off!")#}
		            }
                }
                update(d);
            }

        {% endif%}



	    function addNode() {
            {#alert("addNode");#}
            window.location.href = "add";
		}
		
		function delNode() {
            {#alert("delNode");#}
            window.location.href = "delete";
		}
		
		function mine(name) {
            {#alert(name);#}
            window.location.href = "mine";
		}

		function PBFT(name) {
            {#alert(name);#}
            window.location.href = "PBFT";
		}

		function BGPattack(name) {
            {#alert(name);#}
            window.location.href = "BGPattack";
		}
		
		function createTX(name) {
			{#alert(name);#}
			window.location.href = "send_tx?receive_ip="+$("#receiver").val()+"&amount="+$("#amount").val();
		}


    </script>
</body>
